<template>
  <div class="student-management-container">
    <div class="header">
      <div class="header-left">
        <h1>数据管理页</h1>
        <p class="date">{{currentDate}}</p>
      </div>
      <div class="header-right">
        <el-button type="danger" size="small" @click="logout">退出登录</el-button>
      </div>
    </div>
    
    <div class="student-table">
      <table>
        <thead>
          <tr>
            <th>学员编号</th>
            <th>培训姓名</th>
            <th>联系方式</th>
            <th>已学课程</th>
            <th>学习进度</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="student in students" :key="student.studentId">
            <td>{{ student.studentId }}</td>
            <td>{{ student.studentName }}</td>
            <td>{{ student.studentPhone }}</td>
            <td>{{ student.alreadyLearned || '科目一' }}</td>
            <td>
              <div class="progress-bar">
                <div class="progress" :style="{ width: student.progress || '23%' }"></div>
              </div>
              {{ student.progress || '23%' }}
            </td>
            <td>
              <el-button type="primary" size="small" @click="arrangeForStudent(student.studentId)" style="margin-right: 8px;">编排</el-button>
              <el-button type="info" size="small" @click="viewArrangement(student.studentId)">查看安排</el-button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <span>共 {{ totalStudents }} 条记录</span>
        <div class="page-controls">
          <button @click="previousPage" :disabled="currentPage <= 1">&lt;</button>
          <span class="page-number">{{ currentPage }}</span>
          <button @click="nextPage" :disabled="currentPage >= totalPages">&gt;</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';

const router = useRouter();
const students = ref([]);
const currentPage = ref(1);
const pageSize = 10;
const totalStudents = ref(0);
const currentDate = computed(() => {
  const now = new Date();
  return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
});

const totalPages = computed(() => {
  return Math.ceil(totalStudents.value / pageSize);
});

onMounted(async () => {
  await fetchStudents();
});

const fetchStudents = async () => {
  try {
    // 从后端API获取学生列表
    const response = await axios.get('/api/arrange/students');
    console.log('请求学生列表数据:', response.data);
    
    // 首先检查数据结构并提取学生数组
    let studentArray = [];
    
    if (response.data) {
      // 检查响应结构，判断是否有嵌套的data字段
      if (Array.isArray(response.data)) {
        // 直接是数组
        studentArray = response.data;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        // 数据在 response.data.data 中
        studentArray = response.data.data;
      } else if (typeof response.data === 'object') {
        // 可能是单个学生对象
        studentArray = [response.data];
      }
      
      if (studentArray.length > 0) {
        // 处理响应数据，转换字段名称以匹配模板
        students.value = studentArray.map(student => ({
          studentId: student.student_id || student.studentId,
          studentName: student.student_name || student.studentName,
          studentPhone: student.student_phone || student.studentPhone,
          alreadyLearned: student.already_learned || student.alreadyLearned || '科目一',
          progress: student.progress || '23%'
        }));
        
        totalStudents.value = students.value.length;
        console.log('处理后的学生数据:', students.value);
      } else {
        // 没有有效数据
        students.value = [];
        totalStudents.value = 0;
      }
    } else {
      // 如果没有数据，初始化为空数组
      students.value = [];
      totalStudents.value = 0;
    }
  } catch (error) {
    console.error('获取学生列表失败:', error);
    // 错误时显示空数据，
    students.value = [];
    totalStudents.value = 0;
  }
};

const arrangeForStudent = (studentId) => {
  // 跳转到学员课程信息页面
  router.push(`/course-arrangement/${studentId}`);
};

// 退出登录
const logout = () => {
  // 只清除localStorage中的token和其他认证信息
  localStorage.removeItem('token');
  // 保留课程安排信息，不清除courseArrangements
  
  // 重定向到登录页面
  router.push('/login');
};

// 查看学生安排信息
const viewArrangement = (studentId) => {
  // 从localStorage获取安排信息
  const allArrangements = JSON.parse(localStorage.getItem('courseArrangements') || '{}');
  const studentArrangements = allArrangements[studentId] || [];
  
  console.log('从localStorage获取学生安排信息:', studentArrangements);
  
  if (studentArrangements.length > 0) {
    // 获取最新的安排信息（数组第一个元素）
    const latestArrangement = studentArrangements[0];
    
    // 格式化日期和时间
    const formattedDate = latestArrangement.date || '未指定';
    const timeInfo = `${latestArrangement.startTime || ''}~${latestArrangement.endTime || ''}`;
    
    // 构建详细的安排信息HTML
    let arrangementHtml = `<div class="arrangement-info">
      <p><strong>学员姓名：</strong>${latestArrangement.studentName || '未知'}</p>
      <p><strong>联系方式：</strong>${latestArrangement.studentPhone || '未知'}</p>
      <p><strong>当前课程：</strong>${latestArrangement.courseName || '未安排'}</p>
      <p><strong>教练姓名：</strong>${latestArrangement.coachName || '未分配'}</p>
      <p><strong>安排日期：</strong>${formattedDate}</p>
      <p><strong>时间段：</strong>${timeInfo}</p>
    </div>`;
    
    // 如果有多个安排记录，显示历史记录
    if (studentArrangements.length > 1) {
      arrangementHtml += `<div class="history-title">历史安排记录</div>`;
      
      // 最多显示额外3条历史记录
      const historyLimit = Math.min(3, studentArrangements.length - 1);
      
      for (let i = 1; i <= historyLimit; i++) {
        const history = studentArrangements[i];
        const historyDate = new Date(history.timestamp).toLocaleDateString();
        
        arrangementHtml += `<div class="history-item">
          <p><strong>日期：</strong>${historyDate}</p>
          <p><strong>课程：</strong>${history.courseName || '未知'}</p>
          <p><strong>教练：</strong>${history.coachName || '未知'}</p>
        </div>`;
      }
    }
    
    // 显示安排信息对话框
    ElMessageBox.alert(
      arrangementHtml,
      '学员课程安排信息',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭',
        callback: () => {
          console.log('关闭安排信息对话框');
        }
      }
    );
  } else {
    // 简单提示暂无安排课程
    ElMessage.info('暂无安排课程');
  }
};

const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchStudents();
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchStudents();
  }
};
</script>

<style scoped>
.student-management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

h1 {
  color: #333;
  margin: 0;
}

.date {
  color: #666;
}

.student-table {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.progress-bar {
  width: 150px;
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin-bottom: 5px;
}

.progress {
  height: 100%;
  background-color: #007bff;
  border-radius: 4px;
}

.arrange-btn {
  padding: 6px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.arrange-btn:hover {
  background-color: #0069d9;
}

.pagination {
  display: flex;
  justify-content: space-between;
}

/* 安排信息对话框样式 */
.arrangement-info {
  padding: 10px;
  line-height: 1.8;
}

.arrangement-info p {
  margin: 8px 0;
}

.arrangement-info strong {
  color: #409EFF;
  display: inline-block;
  width: 90px;
}

.history-title {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
  font-weight: bold;
  color: #606266;
}

.history-item {
  margin-top: 8px;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.history-item p {
  margin: 5px 0;
}

.note {
  font-style: italic;
  color: #909399;
  margin-top: 10px;
}

.page-controls {
  display: flex;
  align-items: center;
}

.page-controls button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.page-controls button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-number {
  margin: 0 10px;
  font-weight: bold;
  color: #007bff;
}
</style>
